package com.fs.base.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import org.springframework.stereotype.Service;

import com.fs.base.pojo.MenuMotion;
import com.fs.base.repository.MenuMotionRepository;
import com.fs.base.repository.MenuRepository;

@Service("menuService")
@AllArgsConstructor
public class MenuService {
	@Setter @Getter 
	private MenuMotionRepository menuMotionRepository;
	
	@Setter @Getter 
	private MenuRepository menuRepository;

	@Transactional
	public void configMotion(String menuId,List<MenuMotion> list){
		List<MenuMotion> newLists =new ArrayList<>();
		List<MenuMotion> oldLists =  menuMotionRepository.findByMenuId(menuId);
		
		Map<String,MenuMotion> newMenuIdMotionIdMap = new HashMap<String, MenuMotion>();
		
		Map<String,MenuMotion> hisMenuIdMotionIdMap = new HashMap<String, MenuMotion>();
		for(MenuMotion mm: oldLists){
			hisMenuIdMotionIdMap.put(mm.getMenuId()+"_"+ mm.getMotionId(), mm);
		}
		/*
		 * 新数据新增，旧数据更新
		 */
		String key = null;
		for(MenuMotion m: list){
			key = m.getMenuId()+"_"+ m.getMotionId();
			newMenuIdMotionIdMap.put(key, m);
			if(hisMenuIdMotionIdMap.containsKey(key)){
				m.setId(hisMenuIdMotionIdMap.get(key).getId());
			}
			newLists.add(m);
		}
		//System.out.println("新增："+ JSON.toJSONString(newLists));
		//menuMotionRepository.deleteByMenuId(menuId);
		menuMotionRepository.save(list);
		
		List<MenuMotion> deleteLists = new ArrayList<>();
		for(String k: hisMenuIdMotionIdMap.keySet()){
			if(!newMenuIdMotionIdMap.containsKey(k)){
				deleteLists.add(hisMenuIdMotionIdMap.get(k));
			}
		}
		//System.out.println("删除："+ JSON.toJSONString(deleteLists));
		menuMotionRepository.deleteInBatch(deleteLists);
	}
}
